package com.jin.webvideo.config.filter;

import com.jin.webvideo.base.LoginHandler;
import com.jin.webvideo.config.filter.access.AccessControl;
import com.jin.webvideo.entity.SessionStore;
import com.jin.webvideo.util.consts.CookieConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AccessFilter implements Filter {
    private static final Logger LOGGER = LoggerFactory.getLogger(AccessFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        AccessControl accessControl = AccessControl.getInstance();
        if (servletRequest instanceof HttpServletRequest httpServletRequest) {
            HttpSession session = httpServletRequest.getSession();
            SessionStore sessionStore = LoginHandler.getSessionStore(session);
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            AccessControl.Access access = accessControl.chkAccess(sessionStore, httpServletRequest);
            if (!access.isAllow()) {
                LOGGER.info("{} is forbidden to access the url[{}], code is [{}], info is [{}]",
                        sessionStore==null?httpServletRequest.getRemoteAddr():sessionStore.getTraceId(),
                        httpServletRequest.getRequestURI(),
                        access.getHttpCode(), access.getInformation());
                httpServletRequest.setAttribute("msg", access.getInformation());
                accessControl.recycle(access);
                response.sendError(access.getHttpCode());
                return;
            }

            if (sessionStore == null) {
                sessionStore = new SessionStore();
                httpServletRequest.getSession().setAttribute(CookieConst.SESSION_KEY, sessionStore);
            }
            accessControl.recycle(access);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
